let newsMethod = require("../dao/newsListDAO").newsMethod;

// 新增新闻
exports.addNews = function (req, res){
  newsMethod.findOne({title:req.body.title}, function (err, doc){
    if(!err){
      if(!doc){
        let newNews = {title: req.body.title, content: req.body.content, time: req.body.time};
        newsMethod.save(newNews, function (err){
          if(!err){
            res.send({
              code: 200,
              msg: "新增成功！"
            });
          }
        });
      }else{
        res.send({
          code: 201,
          msg: "标题已被占用！"
        });
      }
    }
  });
};


// 获取新闻列表
exports.getNewsList = function (req, res){
  newsMethod.findAll(function (err, doc) {
    if(!err){
      res.send({
        code: 200,
        data: doc,
        msg: "查询成功！"});
    }
    else{
      res.send({
        code: 201,
        msg: "查询失败！"});
    }
  })
};

// 删除
exports.delNews = function (req, res){
  let id = req.body.id
  // 根据id查询单条数据
  newsMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      let par = {
        _id: id
      }
      // 删除单条数据
      newsMethod.remove(par,function (err, doc) {
        if(!err){
          res.send({
            code: 200,
            msg: "删除成功！"});
        }else{
          res.send({
            code: 200,
            msg: "删除失败！"});
        }
      })
    }
  })
};

// 修改
exports.editNews = function (req, res) {
  let newNews = {title: req.body.title, content: req.body.content};
  // 查询单个数据
  newsMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      // 更新单个数据
      newsMethod.update({_id:req.body.id},newNews,function (err) {
        if(!err){
          res.send({
            code: 200,
            msg: "修改成功！"});
        }
        else{
          res.send({
            code: 201,
            msg: "修改失败！"});
        }
      })
    }
  })
}


// 查询单个
exports.getNewsDetail = function (req, res) {
  // 查询单个数据
  newsMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      if(!err){
        res.send({
          code: 200,
          data:doc,
          msg: "查询成功！"});
      }
      else{
        res.send({
          code: 201,
          msg: "查询失败！"});
      }
    }
  })
}
